﻿using Mate.Core.Base;
using Mate.Framework.Engine;
using Mate.Framework.Extensions;
using Mate.System.Service;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Mate.Framework.Infrastructure
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class AdminAuthorizationAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (filterContext.ActionDescriptor.FilterDescriptors.Any(x => x.Filter.GetType() == typeof(NonAuthorizationAttribute)))
            {
                return;
            }

            var controller = filterContext.Controller as Controller;
            string userNo = filterContext.HttpContext.User.Identity.UserNo();
            var roleId = filterContext.HttpContext.User.Identity.RoleId();
            bool isSuperAdmin = userNo == "admin";
            if (isSuperAdmin)
            {
                return;
            }

            //string areaName = filterContext.RouteData.Values["area"]?.ToString();
            string controllerName = filterContext.RouteData.Values["controller"].ToString();
            string actionName = filterContext.RouteData.Values["action"].ToString();

            if (actionName == "GetList")
            {
                return;
            }

            var adminMenuService = EngineContainerFactory.Context.GetInstance<IRolesService>();
            var menuList = adminMenuService.GetMenuAll(roleId, isSuperAdmin);

            if (!menuList.Any(x => x.controller_name == controllerName && x.action_name == actionName))
            {
                if (filterContext.HttpContext.Request.Method == "POST")
                {
                    var result = new BaseResult();
                    result.ResultCode = ResultCode.Nopermit;
                    result.Message = "您没有权限进行此操作";
                    filterContext.Result = new JsonResult(result);
                }
                else
                {
                    filterContext.Result = new RedirectResult("/Home/Unauthorized");
                }
                return;
            }


        }
    }
}